package com.weixing.mall.provider.controller.ads;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Lists;
import com.weixing.mall.base.exception.BusinessException;
import com.weixing.mall.base.wrapper.Result;
import com.weixing.mall.base.wrapper.ResultUtil;
import com.weixing.mall.core.support.BaseController;
import com.weixing.mall.core.support.auth.SysAuth;
import com.weixing.mall.core.support.auth.SysInfo;
import com.weixing.mall.provider.api.model.vo.SysUserVo;
import com.weixing.mall.provider.api.service.SysUserRpcService;
import com.weixing.mall.provider.model.domain.MediaPlatform;
import com.weixing.mall.provider.model.domain.User;
import com.weixing.mall.provider.model.dto.ads.MediaPlatformDto;
import com.weixing.mall.provider.model.enums.ads.PlatformTypeEunm;
import com.weixing.mall.provider.model.query.MediaPlatformQuery;
import com.weixing.mall.provider.model.vo.ads.MediaPlatformVo;
import com.weixing.mall.provider.service.IMediaPlatformService;
import com.weixing.mall.provider.service.IUserService;
import com.weixing.mall.provider.support.excel.ads.MediaPlatformExcalData;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import jdk.nashorn.internal.runtime.regexp.joni.ScanEnvironment;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

/**
 * @Author wx
 * @Date 2019/8/15 17:01
 * @Version 1.0
 */
@RestController
@RequestMapping("mediaPlatform")
@Api(value = "媒体平台Api", tags = "媒体平台")
public class MediaPlatformController extends BaseController {
    @Autowired
    private IMediaPlatformService mediaPlatformService;
    @Autowired
    private IUserService sysUserService;

    @ApiOperation(value = "查看媒体平台")
    @GetMapping("")
    public Result list(@SysInfo SysAuth auth, MediaPlatformQuery mediaPlatformQuery) {
        return ResultUtil.success(mediaPlatformService.selectOfPage(initMpPage(), mediaPlatformQuery, auth.getUid()));
    }

    @ApiOperation(value = "导出媒体平台数据")
    @GetMapping("exportExcal")
    public void exportExcal(@SysInfo SysAuth auth, MediaPlatformQuery mediaPlatformQuery, HttpServletResponse response) {
        List<MediaPlatformVo> list = mediaPlatformService.selectMediaPlatFromList(mediaPlatformQuery, auth.getUid());
        if (list == null || list.size() == 0) {
            throw new BusinessException("无可用数据导出");
        }
        List<MediaPlatformExcalData> importList = Lists.newArrayList();
        list.forEach(mpv -> {
            MediaPlatformExcalData mped = new MediaPlatformExcalData();
            BeanUtils.copyProperties(mpv, mped);
            mped.setIsEnable(mpv.getIsEnable().getDesp());
            mped.setIsPageSiteEunm(mpv.getIsPageSiteEunm().getDesp());
            mped.setPlateformType(mpv.getPlateformType().getDesp());
            importList.add(mped);
        });
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        try {
            String fileName = URLEncoder.encode("媒体平台", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), MediaPlatformExcalData.class).sheet("sheet1").doWrite(importList);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @ApiOperation(value = "新增/修改")
    @PostMapping("save")
    public Result save(@SysInfo SysAuth auth, MediaPlatformDto mediaPlatformDto) {
        try {
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("plateform_name", mediaPlatformDto.getPlateformName());
            MediaPlatform mediaPlatform1 = mediaPlatformService.getOne(queryWrapper);
            User result = sysUserService.getById(mediaPlatform1.getCreatedBy());

            return ResultUtil.error("媒体平台已经被" + result.getRealName() + "录入");

        } catch (Exception e) {
            e.printStackTrace();
        }
        mediaPlatformDto.setCreatBy(auth.getUid());
        mediaPlatformService.save(mediaPlatformDto);
        return ResultUtil.success();
    }

    @ApiOperation(value = "查看公告池")
    @GetMapping("selectPubPool")
    public Result selectPubPool(MediaPlatformQuery mediaPlatformQuery) {

        return ResultUtil.success(mediaPlatformService.selectOfPagePub(initMpPage(), mediaPlatformQuery));
    }

    @ApiOperation(value = "移入公共池")
    @PostMapping("updateIsPubPool/{ids}")
    public Result updateIsPubPool(@PathVariable("ids") Long[] ids) {
        mediaPlatformService.updateIsPubPool(ids);
        return ResultUtil.success();
    }

    @ApiOperation(value = "认领")
    @PostMapping("claim/{ids}")
    public Result claim(@SysInfo SysAuth auth, @PathVariable("ids") Long[] ids) {
        mediaPlatformService.claim(ids, auth.getUid());
        return ResultUtil.success();
    }

    @ApiOperation(value = "查看媒体平台详情")
    @PostMapping("selectMediaPlatform/{id}")
    public Result selectMediaPlatform(@PathVariable("id") Long id) {
        return ResultUtil.success(mediaPlatformService.selectMediaPlatformEditVo(id));
    }

    @ApiOperation(value = "平台类型列表")
    @GetMapping("getPlatformList")
    public Result getPlatformList() {
        return ResultUtil.success(PlatformTypeEunm.values());
    }

    @ApiOperation(value = "媒体删除")
    @GetMapping("del/{id}")
    public Result del(@PathVariable("id") Long id) {
        mediaPlatformService.del(id);
        return ResultUtil.success();
    }

    @ApiOperation(value = "校验媒体名称是否唯一")
    @GetMapping("checkPlateformNameOnly/{plateformName}")
    public Result checkPlateformNameOnly(@PathVariable("plateformName") String plateformName) {
        //返回 false 已存在不可用   true 不存在可以使用

            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("plateform_name", plateformName);
            MediaPlatform mediaPlatform1 = mediaPlatformService.getOne(queryWrapper);
            if(ObjectUtil.isNotNull(mediaPlatform1)){
                User result = sysUserService.getById(mediaPlatform1.getCreatedBy());
                String msg= ObjectUtil.isEmpty(result)?"":result.getRealName();
                return ResultUtil.error("媒体平台已经被" +msg + "录入");
            }
        return ResultUtil.success(mediaPlatformService.checkPlateformNameOnly(plateformName));
    }
}
